package com.software.levelupandroid.home.ui.todayTask;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.home.adapter.TaskItemAdapter;
import com.software.levelupandroid.utils.DateUtil;
import com.software.levelupandroid.utils.StringUtil;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;

public class TodayTaskFragment extends Fragment {
    private TextView tvYear, tvMonth;
    private Calendar calendar;
    private CalendarView calendarView;
    private LinearLayout llDateTime;
    private RecyclerView recyclerView;
    private TaskItemAdapter itemAdapter;
    private TodayTaskViewModel todayTaskViewModel;
    private List<Task> taskList = new ArrayList<>();
    private String dateString = DateUtil.getNowDate("yyyy年MM月dd日");

    @SuppressLint("MissingInflatedId")
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_today_task, container, false);
        //视图绑定
        initViews(view);
        //实例化ViewModel实例
        initViewModel();

        //展示当前的年份和月份
        showYearAndMon();
        //设置监听器
        setListener();
        //管理RecyclerView
        manageRecyclerView();

        //获取数据
        getData();

        //观察LiveData对象
        observeLiveData();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        todayTaskViewModel.getTasksByDate(getContext(), dateString);
    }

    /**
     * 实例化ViewModel实例
     */
    private void initViewModel() {
        ViewModelProvider viewModelProvider = new ViewModelProvider(this);
        todayTaskViewModel = viewModelProvider.get(TodayTaskViewModel.class);
    }

    /**
     * 观察LiveData对象
     */
    private void observeLiveData() {
//        todayTaskViewModel.getTaskListLiveData().observe(this, new Observer<List<Task>>() {
//            @Override
//            public void onChanged(List<Task> tasks) {
//                if (tasks == null){
//                    Toast.makeText(getContext(), "获取tasks失败", Toast.LENGTH_SHORT).show();
//                    return;
//                }
//                itemAdapter.updateTaskList(tasks);
//            }
//        });

        todayTaskViewModel.getTaskListLiveData().observe(this, new Observer<Resource<List<Task>>>() {
            @Override
            public void onChanged(Resource<List<Task>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        itemAdapter.updateTaskList(listResource.getData());
                    } else if (listResource.isFailure()) {
                        ToastUtil.showToastOnUI(getActivity(), listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        //观察任务完成时经验值的LiveData
        todayTaskViewModel.getIsUpdateLiveData().observe(this, new Observer<Resource<Result>>() {
            @Override
            public void onChanged(Resource<Result> resultResource) {
                if (resultResource != null){
                    if (resultResource.isSuccess()){
                        Result data = resultResource.getData();
                        if (data.getCode().equals("200")){
                            User user = (User) data.getData();
                            if (user != null)
                                //TODO 展示升级的通知提示框
                                ToastUtil.showToastOnUI(getActivity(), "恭喜达到 " + user.getGradeId() + " 级");
                            UserUtil.saveUser(user, getActivity());
                        } else if (data.getCode().equals("201")) {
                            //未达到升级条件
                        } else if (data.getCode().equals("500")) {

                        }
                    } else if (resultResource.isFailure()) {
                        ToastUtil.showToastOnUI(getActivity(), resultResource.getErrorMessage());
                    } else if (resultResource.isLoading()) {

                    }
                }
            }
        });
    }


    //管理RecyclerView
    private void manageRecyclerView() {
        itemAdapter = new TaskItemAdapter(getActivity(), todayTaskViewModel);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        recyclerView.setAdapter(itemAdapter);
    }

    //展示当前的年份和月份
    private void showYearAndMon() {
        calendar = calendarView.getSelectedCalendar();
        int year = calendar.getYear();
        int month = calendar.getMonth();
        tvYear.setText(String.valueOf(year));
        tvMonth.setText(StringUtil.monthToStr(month));
    }

    //设置控件监听器
    private void setListener() {
        //设置对calendarView的日期选择监听事件
        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            //当用户选择的日期超出了允许的范围时，此方法会被调用
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            //当用户选择了一个日期时，此方法会被调用
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                int year = calendar.getYear();
                int month = calendar.getMonth();
                int day = calendar.getDay();
                tvYear.setText(String.valueOf(year));
                tvMonth.setText(StringUtil.monthToStr(month));
                dateString = String.format("%d年%02d月%02d日",year, month, day);

                todayTaskViewModel.getTasksByDate(getActivity(), dateString);

            }
        });

        //设置llDateTime（显示年和月的控件）的监听效果，更新时间显示
        llDateTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置一个日期选择对话框
                DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        //使日历滚动到指定的日期
                        calendarView.scrollToCalendar(year, month+1, day);
                    }
                }, calendar.getYear(), calendar.getMonth()-1, calendar.getDay());
                //显示日期选择对话框
                datePickerDialog.show();
            }
        });

    }

    /**
     * 获取后端的数据
     */
    private void getData() {
        todayTaskViewModel.getTasksByDate(getActivity(), DateUtil.getNowDate("yyyy年MM月dd日"));
    }

    //视图绑定
    private void initViews(@NonNull View view) {
        tvYear = view.findViewById(R.id.tv_personalTask_year);
        tvMonth = view.findViewById(R.id.tv_personalTask_month);
        calendarView = view.findViewById(R.id.cv_personalTask);
        llDateTime = view.findViewById(R.id.ll_personalTask_dateTime);
        recyclerView = view.findViewById(R.id.rv_personalTask);

    }

    @SuppressLint("NewApi")
    private void initData() {
        taskList = new ArrayList<>();
        Task task1 = new Task();
        task1.setTaskId(1);
        task1.setTaskTitle("背单词");
        task1.setStartTime("2024-5-1 9:00");
        task1.setEndTime("2024-5-1 12:00");
        task1.setTaskType(2);
        task1.setPriority(3);
        task1.setStatus(1);
        taskList.add(task1);

        Task task2 = new Task();
        task2.setTaskId(2);
        task2.setTaskTitle("写作业");
        task2.setStartTime("2024-5-1 13:00");
        task2.setEndTime("2024-5-1 13:30");
        task2.setTaskType(2);
        task2.setPriority(3);
        task2.setStatus(-1);
        taskList.add(task2);

        Task task3 = new Task();
        task3.setTaskId(3);
        task3.setTaskTitle("吃饭");
        task3.setStartTime("2024-5-1 14:00");
        task3.setEndTime(null);
        task3.setTaskType(1);
        task3.setPriority(0);
        task3.setStatus(0);
        taskList.add(task3);

        Task task4 = new Task();
        task4.setTaskId(4);
        task4.setTaskTitle("锻炼");
        task4.setStartTime("2024-5-1 21:00");
        task4.setEndTime("2024-5-1 21:30");
        task4.setTaskType(1);
        task4.setPriority(1);
        task4.setStatus(0);
        taskList.add(task4);

        Task task5 = new Task();
        task5.setTaskId(5);
        task5.setTaskTitle("吃饭");
        task5.setStartTime("2024-5-1 12:00");
        task5.setEndTime(null);
        task5.setTaskType(0);
        task5.setPriority(0);
        task5.setStatus(0);
        taskList.add(task5);

        Task task6 = new Task();
        task6.setTaskId(6);
        task6.setTaskTitle("锻炼");
        task6.setStartTime("2024-5-1 21:00");
        task6.setEndTime("2024-5-1 21:00");
        task6.setTaskType(1);
        task6.setPriority(1);
        task6.setStatus(0);
        taskList.add(task6);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        todayTaskViewModel.getTaskListLiveData().removeObservers(this);
    }
}